# coding=utf-8
"""
Created on 2018年8月9日
"""
import unittest
import time
import requests
from protobuf_to_dict import dict_to_protobuf, protobuf_to_dict

from util_base.common_utils import ComplexEncoder
import json
import hashlib
import base64
from protobuf_base import protobuf


class TestCases(unittest.TestCase):

    # run before each test method
    def setUp(self):
    
        
        self.host = "http://127.0.0.1"
#         self.host = "http://wallet-dev.tataufo.com"
        
        self.port = 23000
#         self.port = 80
        
       
        self.app_id = 'ttc_wallet'
        self.secretKey = '8cba3720d8ca1e8775141db48b5d6970'

        self.uri = '/v1/'
        self.url = '%s:%s%s' % (self.host, self.port, self.uri)
        pass

    # run after each test method
    def tearDown(self):
        pass

    def test_10000(self):
        """
        test
        """

        cmdid = 10000

        headers = {
                   "AppID": self.app_id,"NonceStr":'a'*32,
                   "Timestamp": str(int(time.time() * 1000)),
                   "SignType":'md5',
                   "RequestSign":'kkkkkk',
                   'cmdId': str(cmdid)
                   }

        body = {
                "common": {
                    'userId': 'xxxx',
                    'cmdId': cmdid,
                    'release': 1,
                    'platform':2
                },
                "params": {
                     
                }
        }
       
        body = (dict_to_protobuf(getattr(protobuf, 'Request%s'% cmdid), body)).SerializeToString()
        
        sign_str = '''AppID=%s&Body=%s&NonceStr=%s&SignType=md5&Timestamp=%s&secretKey=%s'''%(self.app_id,
                                                                                               base64.b64encode(body).decode('utf-8'), headers['NonceStr'],
                                                                                               headers['Timestamp'], self.secretKey)
#         print sign_str
        headers['RequestSign'] = hashlib.md5(sign_str.encode('utf-8')).hexdigest().upper()
        
        start = time.time()
        res = requests.post(self.url, data=body, headers=headers)
        end = time.time()

        self._print_response(cmdid, res)

        print('...耗时%sms...' % ((end - start) * 1000))

    def _print_response(self, cmdid, res):
        try:
            res_msg = getattr(protobuf, 'Response%s' % cmdid)()
            res_msg.ParseFromString(res.content)
            print(json.dumps(protobuf_to_dict(res_msg), indent=4, cls=ComplexEncoder))
        except:
            print(res.content)
        

if __name__ == '__main__':
    suite = unittest.TestSuite()
    suite.addTest(TestCases('test_10001'))
    unittest.TextTestRunner(verbosity=2).run(suite)
